package com.demo.rpc.client;

import com.demo.rpc.common.RpcRequest;
import com.demo.rpc.common.RpcResponse;
import com.demo.rpc.zk.ZkClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ServiceProxyFactory implements InvocationHandler {
    private ZkClient zkClient;
    private String monitorServer;

    public ServiceProxyFactory(ZkClient zkClient) {
        this.zkClient = zkClient;
    }

    public ServiceProxyFactory(String monitorServer) {
        this.monitorServer = monitorServer;
    }


    public <T> T getProxy(Class<T> clazz) {
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz}, ServiceProxyFactory.this);
    }

    @Override
    public Object invoke(Object obj, Method method, Object[] params) throws Throwable {
        RpcRequest request = new RpcRequest();
        request.setMethodName(method.getName());
        request.setParameterTypes(method.getParameterTypes());
        request.setClassName(method.getDeclaringClass().getName());
        request.setParameters(params);
        //获取服务器地址
        String server = null;
        if (monitorServer == null) {
            server = zkClient.getServer();
        } else {
            server = monitorServer;
        }
        if (server == null) {
            throw new RuntimeException("找不到服务器");
        }
        String[] sv = server.split(":");
        RpcClientHandler client = new RpcClientHandler(sv[0], Integer.parseInt(sv[1]));
        //获取发送请求
        RpcResponse response = client.send(request);
        if (response.getError() != null) {
            throw response.getError();
        }
        return response.getResult();
    }
}
